﻿--lua script

--#include "data\config\guild\Guild.lua" once 
--#include "data\config\guild\GuildSiegeConfig.lua" once 
--#include "data\functions\Common\RankMgr.lua" once 		--排行榜管理
--#include "data\functions\Activity\OpenServer\OpenServerGuildSbkWar.lua" once
--#include "data\functions\Activity\CombineServer\CombineServerGuildSbkWar.lua" once

--行会一些定时执行的函数

-- 是否攻城时间
function CheckSbkGuildWarTime()
	local SbkSignUpTime = GuildConfig.SbkSignUpTime
	
	local nDays = System.getDaysSinceOpenServer()
	if nDays < SbkSignUpTime.openDay then
		return false
	elseif nDays == SbkSignUpTime.openDay then
		return true
	end
	
	if SbkSignUpTime.combineDay >= 0 then
		nDays = System.getDaysSinceCombineServer()
		if nDays > 0 then -- 合过服了
			if nDays < SbkSignUpTime.combineDay then
				return false
			elseif nDays == SbkSignUpTime.combineDay then
				return true
			end
		end		
	end
	
	nDays = System.getDayOfWeek()
	local state = SbkSignUpTime.weekStates[nDays + 1]
	if state == 1 then -- 攻城时间
		return true
	end	
	
	return false	-- 非攻城时间
end

--沙巴克期间
function IsSbkWarStarting()
	local sdvar = System.getDyanmicVar()
	if sdvar.sbkWarStartTime and sdvar.sbkWarStartTime > 0 then
		return true
	end
	return false
end

--沙巴克检测占领期间
function IsSbkWarCheckWinGuild()
	local sdvar = System.getDyanmicVar()
	if sdvar.sbkCheckWinGuild == 1 then
		return true
	end
	return false
end

--雕像是否还存在
function IsSbkStatusLiving()
	local sdvar = System.getDyanmicVar()
	if sdvar.sbkStatusLive == 1 then
		return true
	end
	return false
end

--停止报名，去掉占领方的外观
function SbkBackAppearAndStopSign()
	if not CheckSbkGuildWarTime() then return end

	local sdvar = System.getDyanmicVar()
	sdvar.sbkOldGuildMaxScoreGuildId = sdvar.sbkGuildMaxScoreGuildId
	sdvar.sbkGuildMaxScoreGuildId = nil

	System.stopSbkGuildWarSign()
	
	Guild.clearSbkGuildPosition()

	DeleteSbkTitle()

	InitNpcStatueName()

	--排行榜数据清理	
	gRankMgr_Clear(RANK_SBK_SCORE)
	gRankMgr_Clear(RANK_SBK_GUILD_SCORE)
	gRankMgr_Clear(RANK_SBK_WIN_GUILD_PLAYERS)
	gRankMgr_Clear(RANK_SBK_MAXSCORE_PLAYERS)


	SaveGuildRank()
	gRankMgr_Save(RANK_SBK_GUILD_LIST)
end

--沙巴克战预告
function SbkGuildWarNotice()
	if not CheckSbkGuildWarTime() then return end
	System.broadcastTipmsg(Lang.GuildLang.z00056, ttScreenCenter) -- 攻城战将在10分钟后开启
end

--沙巴克城战开始
function StartSbkGuildWar()
	if not CheckSbkGuildWarTime() then return end	
	local sdvar = System.getDyanmicVar()
	sdvar.sbkWarStartTime = System.getCurrMiniTime()

	--排行榜数据清理	
	gRankMgr_Clear(RANK_SBK_SCORE)
	gRankMgr_Clear(RANK_SBK_GUILD_SCORE)
	gRankMgr_Clear(RANK_SBK_WIN_GUILD_PLAYERS)
	gRankMgr_Clear(RANK_SBK_MAXSCORE_PLAYERS)

	System.startSbkGuildWar()

	Actor.unregScriptCallback(System.getGlobalNpc(), "OnGetSbkExpInTheMap")
	Actor.regScriptTimer(System.getGlobalNpc(), 0, GuildSiegeConfig.LoopTime, GuildSiegeConfig.LoopTime, 1, "OnGetSbkExpInTheMap") 	

	CreateSbkStatus()

	OnSendSbkPanelStateAll(1)
	OnSendSbkDataAll()

	local siegeSceneList = {GuildSiegeConfig.PalaceSceenId, GuildSiegeConfig.FightSceenId}
	for i,v in ipairs(siegeSceneList) do
		local playerList = LuaHelp.getSceneActorListById(v) or {}
		for i2,v2 in ipairs(playerList) do
			if Actor.isSignUpSbkWar(v2) then
				local playVar = Actor.getStaticVar(v2)
				if not playVar.days then playVar.days = {} end
				if not playVar.days.sbkWarState then
					Actor.triggerAchieveEvent(v2, 44, 2)
					playVar.days.sbkWarState = 1
				end
				OnSbkSetDeadRelivePos(v2)
				Actor.updateActorName(v2)
			end
		end
	end

	System.broadcastTipmsg(Lang.GuildLang.GuildSeige001 ,ttScreenCenter + ttChatWindow)

	changeSaveGuildRank()
	gRankMgr_Save(RANK_SBK_GUILD_LIST)
end

--沙巴克城战开始检测占领行会
function SkbStartCheckWinGuild()
	if not CheckSbkGuildWarTime() then return end	
	local sdvar = System.getDyanmicVar()
	sdvar.sbkCheckWinGuild = 1

	local dVar = System.getDyanmicVar()
	dVar.guildSbkTempOccupyGuildId = System.getOldSbkGuildId()

	OnSbkCheckTempOccupy(GuildSiegeConfig.FightSceenId)

	changeSaveGuildRank()
	gRankMgr_Save(RANK_SBK_GUILD_LIST)
end

--进入场景
function onSbkEnterScene(sysarg, sceneId, lastSceneId)
	if not CheckSbkGuildWarTime() then return end	
	if not IsSbkWarStarting() then
		return
	end

	if not Actor.isSignUpSbkWar(sysarg) and sceneId == GuildSiegeConfig.FightSceenId and lastSceneId == GuildSiegeConfig.PalaceSceenId then
		Actor.sendTipmsg(sysarg, Lang.GuildLang.GuildSeige022, ttFlyTip)
		Actor.enterScene( sysarg, unpack(GuildSiegeConfig.exitPos))
		return 
	elseif Actor.isSignUpSbkWar(sysarg) and sceneId == GuildSiegeConfig.FightSceenId and lastSceneId == GuildSiegeConfig.PalaceSceenId then
		System.telportRandPos(sysarg)
	end
	
	OnSbkCheckTempOccupy(sceneId)

	if Actor.isSignUpSbkWar(sysarg) and sceneId == GuildSiegeConfig.PalaceSceenId and lastSceneId ~= GuildSiegeConfig.FightSceenId then
		OnSbkSetDeadRelivePos(sysarg)
		OnSendSbkPanelState(sysarg, 1)
		OnSendSbkData(sysarg)
		local sVar = Actor.getStaticVar(sysarg)
		if not sVar.days then sVar.days = {} end
		if not sVar.days.sbkWarState then
			Actor.triggerAchieveEvent(sysarg, 44, 2)
			sVar.days.sbkWarState = 1
		end	
		--Actor.updateActorName(sysarg) 			--此处由于区域属性改变导致名字会自动刷新，不需要再广播名字颜色改变
	elseif Actor.isSignUpSbkWar(sysarg) and lastSceneId == GuildSiegeConfig.PalaceSceenId and sceneId ~= GuildSiegeConfig.FightSceenId then
		OnSendSbkPanelState(sysarg, 0)
		Actor.updateActorName(sysarg)
	elseif Actor.isSignUpSbkWar(sysarg) then
		OnSendSbkData(sysarg)
	end
end

--沙巴克城战检测占领行会
function OnSbkCheckTempOccupy(nSceneId, finalCheck)
	local FightSceenId = GuildSiegeConfig.FightSceenId
	if nSceneId then
		if nSceneId ~= FightSceenId then
			return
		end
	end

	if not CheckSbkGuildWarTime() then
		return
	end

	if not IsSbkWarStarting() then
		return
	end 

	if not IsSbkWarCheckWinGuild() then
		return
	end

	
	local dVar = System.getDyanmicVar()
	local nTempOccupyGuildId = dVar.guildSbkTempOccupyGuildId or 0 -- 临时占领的行会


	local nCheckGuildId = 0 --用来检查是否只有一个行会在皇宫临时占领
	local playerList = LuaHelp.getSceneActorListById( FightSceenId ) or {}
	local playerNum = 0
	for i,v in ipairs(playerList) do
		local myGuildId = Actor.getGuildId(v)
		if Actor.isSignUpSbkWar(v) and not Actor.isDeath(v) then
			playerNum = playerNum + 1
			if nCheckGuildId == 0 then
				nCheckGuildId = Actor.getGuildId(v)
			elseif nCheckGuildId ~= myGuildId then--超过一个行会
				return
			end
		end
	end

	if nCheckGuildId ~= 0 and nCheckGuildId ~=  nTempOccupyGuildId then --临时占领易主

		dVar.guildSbkTempOccupyGuildId = nCheckGuildId
		System.broadcastTipmsg(string.format(Lang.GuildLang.GuildSeige003, Guild.getGuildName(nCheckGuildId)),ttScreenCenter + ttChatWindow)
		OnSendSbkDataAll()
	end

	if playerNum == 0 and finalCheck and not IsSbkStatusLiving() then
		dVar.guildSbkTempOccupyGuildId = 0
	end
end

--城战结束
function EndSbkGuildWar()
	if not CheckSbkGuildWarTime() then return end	
	local sdvar = System.getDyanmicVar()
	sdvar.sbkCheckWinGuild = nil

	if IsSbkWarStarting() then
		Actor.unregScriptCallback(System.getGlobalNpc(), "OnGetSbkExpInTheMap")


		OnSbkCheckTempOccupy(GuildSiegeConfig.FightSceenId ,true)

		if sdvar.guildSbkTempOccupyGuildId  and sdvar.guildSbkTempOccupyGuildId ~= 0 then
			System.setSbkGuildId(sdvar.guildSbkTempOccupyGuildId)

			System.broadcastTipmsg(string.format(Lang.GuildLang.GuildSeige005, Guild.getGuildName(sdvar.guildSbkTempOccupyGuildId)),ttScreenCenter + ttChatWindow)
		else
			System.broadcastTipmsg(Lang.GuildLang.GuildSeige004,ttScreenCenter + ttChatWindow)
		end
		sdvar.guildSbkTempOccupyGuildId = nil

		System.endSbkGuildWar()

		SendSbkReward()

		OnSendSbkPanelStateAll(0)

		KickAllPlayerInPalace()

		local playerList = LuaHelp.getSceneActorListById(GuildSiegeConfig.PalaceSceenId) or {}
		for k , v in ipairs(playerList) do
			if Actor.isSignUpSbkWar(v) then
				OnSbkSetDeadRelivePos(v, true)
				Actor.updateActorName(v)
			end
		end

		InitNpcStatueName()

		OnOpenServerGuildSiegeOverHandle()

		OnCombineServerGuildSiegeOverHandle()

		OnOldSbkGuildResetName()

		changeSaveGuildRank()
		gRankMgr_Save(RANK_SBK_GUILD_LIST)

		System.startSbkGuildWarSign()	
	end
	System.setSbkSignState(1)
	sdvar.sbkWarStartTime = nil

	--sdvar.guildSeigeTaxCanGet = 1
end


--在攻城期间离开场景
function OnSbkActorExitScene(sysarg, sceneId)
	if not CheckSbkGuildWarTime() then return end	
	if not IsSbkWarStarting() then
		return
	end

	local FightSceenId = GuildSiegeConfig.FightSceenId
	if FightSceenId ~= sceneId then
		return
	end

	if IsSbkWarCheckWinGuild() then
		OnSbkCheckTempOccupy(sceneId)
	end
end

--在攻城期间死亡
function OnSbkActorDead(sysarg)
	if not CheckSbkGuildWarTime() then return end	
	if not IsSbkWarStarting() then
		return
	end
	local sceneId = Actor.getSceneId(sysarg)
	local FightSceenId = GuildSiegeConfig.FightSceenId
	if FightSceenId ~= sceneId then
		return
	end
	if IsSbkWarCheckWinGuild() then
		OnSbkCheckTempOccupy(sceneId)
	end
end


--上线 活动期间
--行会攻城时 
function OnSbkActorLogin(sysarg)
	if not CheckSbkGuildWarTime() then return end	
	if not IsSbkWarStarting() then
		return
	end
	local sceneId = Actor.getSceneId(sysarg)
	local FightSceenId = GuildSiegeConfig.FightSceenId
	local PalaceSceenId = GuildSiegeConfig.PalaceSceenId
	if sceneId ~= PalaceSceenId or sceneId ~= FightSceenId then
		return
	end
	if Actor.isSignUpSbkWar(sysarg) then
		OnSbkSetDeadRelivePos(sysarg)
		OnSendSbkPanelState(sysarg, 1)
		OnSendSbkData(sysarg)
		Actor.updateActorName(sysarg)
	end
end
--行会攻城时下线
function OnGuildSiegeLogout(sysarg)
	if not CheckSbkGuildWarTime() then return end	
	if not IsSbkWarStarting() then
		return
	end
	local sceneId = Actor.getSceneId(sysarg)
	local FightSceenId = GuildSiegeConfig.FightSceenId
	local PalaceSceenId = GuildSiegeConfig.PalaceSceenId
	if sceneId ~= PalaceSceenId or sceneId ~= FightSceenId then
		return
	end
	
	if Actor.isSignUpSbkWar(sysarg) then
		OnSbkSetDeadRelivePos(sysarg, true)--下线时把复活点设出去
		OnSbkActorExitScene(sysarg, sceneId)--下线的时候先触发一下，
	end
end

--设置重生点
function OnSbkSetDeadRelivePos(sysarg, logout)

	local resetState = IsSbkStatusLiving()

	local nGuildId = Actor.getGuildId(sysarg)
	--local sVar = System.getStaticVar()

	local relive
	if IsSbkWarStarting() then
		relive = GuildSiegeConfig.relivePosAfterEnterPalace
	else
		relive = GuildSiegeConfig.relivePos
	end
	if System.getOldSbkGuildId() == nGuildId and resetState then
		relive = GuildSiegeConfig.relivePosBeforeEnterPalace
	end 

	if logout then
		relive = GuildSiegeConfig.relivePos
	end
	local posX = math.min(relive[1],relive[3]) + System.getRandomNumber(math.abs(relive[3]- relive[1]) + 1)
	local posY = math.min(relive[2],relive[4]) + System.getRandomNumber(math.abs(relive[2]- relive[4]) + 1)
	Actor.SetRelivePoint(sysarg, posX, posY, relive[5], false)
end 

--获取攻城剩余时间
function GetSbkLeftTime()
	if not IsSbkWarStarting() then
		return 0
	end 
	local dVar = System.getDyanmicVar()
	local nCurTime = System.getCurrMiniTime()
	local nLeftTime = (dVar.sbkWarStartTime or 0) + GuildSiegeConfig.SbkActivityTime - nCurTime
	return nLeftTime
end


--创建sbk皇宫入口雕像
function CreateSbkStatus()
	freshSceneMonsterInPosForce(GuildSiegeConfig.statusMonster)
	local dVar = System.getDyanmicVar()
	dVar.sbkStatusLive = 1

end

--sbk皇宫入口雕像死亡
function OnSbkStatusDie(monster, monId)
	if not IsSbkWarStarting() then
		return
	end
	
	local cfg = GuildSiegeConfig.statusMonster

	if monId ~= cfg.monsterId then
		return
	end
	local dVar = System.getDyanmicVar()
	dVar.sbkStatusLive = nil
	 
	SetPalaceTeleportVisible(true)

	System.broadcastTipmsg(Lang.GuildLang.GuildSeige002, ttScreenCenter + ttChatWindow)

	ChangeLastWinGuildRelivePos()

	changeSaveGuildRank()

	gRankMgr_Save(RANK_SBK_GUILD_LIST)
end


--重置守城行会出生点
function ChangeLastWinGuildRelivePos()
	local lastWinGuildId = System.getOldSbkGuildId()
	local siegeSceneList = {GuildSiegeConfig.PalaceSceenId, GuildSiegeConfig.FightSceenId}
	for i,v in ipairs(siegeSceneList) do
		local playerList = LuaHelp.getSceneActorListById(v) or {}
		for i2,v2 in ipairs(playerList) do
			if Actor.getGuildId(v2) == lastWinGuildId and Actor.isSignUpSbkWar(v2) then
				OnSbkSetDeadRelivePos(v2)
			end
		end
	end
end

--发送攻城战右侧面板开启或者关闭
function OnSendSbkPanelStateAll(value)
	local siegeSceneList = {GuildSiegeConfig.PalaceSceenId, GuildSiegeConfig.FightSceenId}
	for i,v in ipairs(siegeSceneList) do
		local playerList = LuaHelp.getSceneActorListById(v) or {}
		for i2,v2 in ipairs(playerList) do
			if Actor.isSignUpSbkWar(v2) then
				OnSendSbkPanelState(v2, value)
			end
		end
	end
end

--发送城战信息给所有皇宫和皇城的人
function OnSendSbkDataAll()
	local siegeSceneList = {GuildSiegeConfig.PalaceSceenId, GuildSiegeConfig.FightSceenId}
	for i,v in ipairs(siegeSceneList) do
		local playerList = LuaHelp.getSceneActorListById(v) or {}
		for i2,v2 in ipairs(playerList) do
			if Actor.isSignUpSbkWar(v2) then
				OnSendSbkData(v2)
			end
		end
	end
end

--发送城战信息
function OnSendSbkData(sysarg)
	if not IsSbkWarStarting() then
		return
	end
	local netPack = DataPack.allocPacket(sysarg, enGuildSystemID, 76) --sGuildSbkRightPanelInfo
	

	local sdvar = System.getDyanmicVar()
	local lastTime = GetSbkLeftTime()
	DataPack.writeInt(netPack, lastTime)	


	local CurGuildName = ""
	if IsSbkWarCheckWinGuild() then
		CurGuildName = Guild.getGuildName(sdvar.guildSbkTempOccupyGuildId)
	else
		CurGuildName = Guild.getGuildName(System.getOldSbkGuildId())
	end
	DataPack.writeString(netPack, CurGuildName or "")

	local rankPtr = Ranking.getRanking(RankList[RANK_SBK_GUILD_SCORE].strName)
	local rankCount = Ranking.getRankItemCount(rankPtr)
	local nCount = 3
	DataPack.writeByte(netPack, nCount)
	if rankPtr then
		if rankCount < 3 then 
			nCount = rankCount
		end
		for idx = 1, 3 do
			if idx > nCount then
				DataPack.writeString(netPack, "")
				DataPack.writeInt(netPack, 0)	
			else
				local item = Ranking.getItemFromIndex(rankPtr, idx-1)
				if item then
					local guildId = tonumber(Ranking.getId(item))
					local point = tonumber(Ranking.getPoint(item))

					local guildName = Guild.getGuildName(guildId) or ""
					DataPack.writeString(netPack, guildName)
					DataPack.writeInt(netPack, point)
				end
			end
		end
	else
		for idx = 1, 3 do
			DataPack.writeString(netPack, "")
			DataPack.writeInt(netPack, 0)	
		end
	end

	local mypoint = 0

	local rankScorePtr = Ranking.getRanking(RankList[RANK_SBK_SCORE].strName)
	if rankScorePtr then
		local item  = Ranking.getItemPtrFromId(rankScorePtr, Actor.getActorId(sysarg))
		if item then
			mypoint = tonumber(Ranking.getPoint(item))
		end
	end

	DataPack.writeInt(netPack, mypoint)	

	DataPack.flush(netPack)
	
end

--发送开启关闭面板
function OnSendSbkPanelState(sysarg, state)
	local netPack = DataPack.allocPacket(sysarg, enGuildSystemID, 74) --sSendSbkRightPanelState
	DataPack.writeInt(netPack, state)	
	DataPack.flush(netPack)
end



-- 领取泡点奖励
function OnGetSbkExpInTheMap()
	Actor.unregScriptCallback(System.getGlobalNpc(), "OnGetSbkExpInTheMap")

	if not CheckSbkGuildWarTime() then return end	
	if not IsSbkWarStarting() then
		return
	end

	Actor.regScriptTimer(System.getGlobalNpc(), 0, GuildSiegeConfig.LoopTime, GuildSiegeConfig.LoopTime, 1, "OnGetSbkExpInTheMap") 	

	local siegeSceneList = {GuildSiegeConfig.PalaceSceenId, GuildSiegeConfig.FightSceenId}
	for i,v in ipairs(siegeSceneList) do
		local playerList = LuaHelp.getSceneActorListById(v) or {}
		for i2,v2 in ipairs(playerList) do
			if Actor.isSignUpSbkWar(v2) and Actor.hasMapAreaAttri(v2, aaPaoDianAddExpArea) then
				--local actorLevel = Actor.getIntProperty(v2,PROP_CREATURE_LEVEL)
				local logId = LogIds.SbkWarExpLogId
				local logStr = Lang.LogTips.SbkWarExp
				GiveCommonAward(v2 , GuildSiegeConfig.LoopExp , logId, logStr)
			end
		end
	end

end


--传送点设成可见/不可见
function SetPalaceTeleportVisible(isVisible)
	local hScene = Fuben.getSceneHandleById(GuildSiegeConfig.teleport.sceneId, 0)
	System.setTeleportVisible(isVisible,hScene,GuildSiegeConfig.teleport.posX,GuildSiegeConfig.teleport.posY)
end
--获取传送点是否可见
function IsPalaceTeleportVisible()
	local hScene = Fuben.getSceneHandleById(GuildSiegeConfig.teleport.sceneId, 0)
	return System.isTeleportVisible(hScene,GuildSiegeConfig.teleport.posX,GuildSiegeConfig.teleport.posY)
end

--沙巴克期间杀人
function OnSbkActorKillPlayers(sysarg, beKilledPlayer)
	if not CheckSbkGuildWarTime() then
		return 
	end

	if not IsSbkWarStarting() then
		return 
	end

	if Actor.isMonster(sysarg) then
		return
	end

	local sceneId = Actor.getSceneId(sysarg)
	local FightSceenId = GuildSiegeConfig.FightSceenId
	local PalaceSceenId = GuildSiegeConfig.PalaceSceenId
	if sceneId ~= PalaceSceenId and sceneId ~= FightSceenId then
		return
	end

	if not Actor.isSignUpSbkWar(sysarg) or not Actor.isSignUpSbkWar(beKilledPlayer) then
		return 
	end

	--local actorLevel = Actor.getIntProperty(beKilledPlayer,PROP_CREATURE_LEVEL)
	--local actorCircle = Actor.getIntProperty(beKilledPlayer, PROP_ACTOR_CIRCLE)

	for idx = 1, #GuildSiegeConfig.killScore do
		local value = GuildSiegeConfig.killScore[idx]
		if Actor.checkActorLevel(beKilledPlayer, value.level, value.circle) then
			--增加个人榜积分
			local actorId = Actor.getActorId(sysarg)
			gRankMgr_AddValue(actorId, RANK_SBK_SCORE, value.addScore)

			--增加行会榜积分
			
			local guildId = Actor.getGuildId(sysarg)
			if guildId and guildId > 0 then
				local guildName = Guild.getGuildName(guildId)
				gRankMgr_AddValue(guildId, RANK_SBK_GUILD_SCORE, value.addScore, guildName)
			end
			OnSendSbkDataAll()
			break
		end
	end
end

--计算排行榜
function GuildCalcGuildScore()
	local winGuildId = System.getSbkGuildId()
	local rankPtr = Ranking.getRanking(RankList[RANK_SBK_SCORE].strName)
	local rankGuildPtr = Ranking.getRanking(RankList[RANK_SBK_GUILD_SCORE].strName)
	local rankCount = Ranking.getRankItemCount(rankPtr)
	--print("GuildCalcGuildScore rankCount = "..rankCount)
	local maxScoreGuildId = 0
	if rankGuildPtr then
		local item = Ranking.getItemFromIndex(rankGuildPtr, 0)
		if item then
			maxScoreGuildId = tonumber(Ranking.getId(item))
			--print("GuildCalcGuildScore maxScoreGuildId = "..maxScoreGuildId)
		end
		if winGuildId and winGuildId ~= 0 and maxScoreGuildId == winGuildId then
			local item = Ranking.getItemFromIndex(rankGuildPtr, 1)
			if item then
				maxScoreGuildId = tonumber(Ranking.getId(item))
				--print("GuildCalcGuildScore maxScoreGuildId = "..maxScoreGuildId)
			else
				maxScoreGuildId = 0
			end
		end
	end
	if rankPtr then
		--print("GuildCalcGuildScore winGuildId ="..winGuildId)
		for idx = 1, rankCount do
			--print("GuildCalcGuildScore idx = "..idx)
			local item = Ranking.getItemFromIndex(rankPtr, idx - 1)
			if item then
				local actorId = tonumber(Ranking.getId(item))
				--print("GuildCalcGuildScore actorId =".. actorId)
				local guildId = Actor.getGuildId(Actor.getActorById(actorId))
				--print("GuildCalcGuildScore guildId =".. guildId)
				local actorScore = tonumber(Ranking.getPoint(item))
				if guildId and guildId == winGuildId then
					--print("GuildCalcGuildScore guildId ="..guildId)
					--print("GuildCalcGuildScore actorId ="..actorId)
					gRankMgr_AddValue(actorId, RANK_SBK_WIN_GUILD_PLAYERS, actorScore)
				end
				if guildId and guildId == maxScoreGuildId then 
					--print("GuildCalcGuildScore guildId ="..guildId)
					--print("GuildCalcGuildScore actorId ="..actorId)
					gRankMgr_AddValue(actorId, RANK_SBK_MAXSCORE_PLAYERS, actorScore)
				end
			end
		end	
	end
	return maxScoreGuildId
end

--发送sbk奖励
function SendSbkReward()
	local maxScoreGuildId = GuildCalcGuildScore()
	--print("SendSbkReward maxScoreGuildId = "..maxScoreGuildId)
	local sdvar = System.getDyanmicVar()
	sdvar.sbkOldGuildMaxScoreGuildId = nil
	sdvar.sbkGuildMaxScoreGuildId = maxScoreGuildId
	SendSbkWinGuildReward()
	SendSbkScoreGuildReward(maxScoreGuildId)

	SendSbkTitle()

	SendSbkCityPosition()
end

--给官员发官职
function SendSbkCityPosition()
	local winGuildId = System.getSbkGuildId()

	if not winGuildId then
		return
	end

	if winGuildId == 0 then
		return
	end

	local pGuild = Guild.getGuild(winGuildId)
	if not pGuild then
		return
	end

	local leader = Guild.getGuildLeaderId( winGuildId )
	if leader > 0 then
		Guild.setSbkGuildPosition(leader, stRealMaster)
	end
	local nextLeader = Guild.getGuildSecLeaderId( winGuildId )
	if nextLeader > 0 then
		Guild.setSbkGuildPosition(nextLeader, stAssistMaster)
	end
	local general1,general2,general3 = Guild.getGuildTangzhuId(winGuildId,0,0,0)
	if general1 > 0 then
		Guild.setSbkGuildPosition(general1, stGeneral1)
	end
	if general2 > 0 then
		Guild.setSbkGuildPosition(general2, stGeneral2)
	end
	if general3 > 0 then
		Guild.setSbkGuildPosition(general3, stGeneral3)
	end
end

--胜利行会称号下发
function SendSbkTitle()
	local winGuildId = System.getSbkGuildId()

	if not winGuildId then
		return
	end
	if winGuildId == 0 then
		return
	end
	local pGuild = Guild.getGuild(winGuildId)
	local guildLeaderId = Guild.getSbkCityOwner()
	local onLineGuildPlayers = LuaHelp.getGuildMemberList(pGuild) or {}
	for idx,player in ipairs(onLineGuildPlayers) do
		local actorId = Actor.getActorId(player)
		Actor.ResetShowName(player)
		if actorId == guildLeaderId then
			Actor.setSocialMask(player, smIsSbkCityMaster, true)
			Actor.addTopTitle(player,Title.SbkOwner)
			Actor.addBuffById(player, GuildSiegeConfig.dragonRoleBuffId)
		else
			--Actor.addTopTitle(player,Title.SbkMember)
			local vocation = Actor.getIntProperty(player, PROP_ACTOR_VOCATION)
			for idx = 1, #GuildSiegeConfig.normalRoleBuffId[vocation] do
				if not Actor.hasBuffById(player, GuildSiegeConfig.normalRoleBuffId[vocation][idx]) then
					Actor.addBuffById(player, GuildSiegeConfig.normalRoleBuffId[vocation][idx])
				end
			end
		end
	end
end

--行会称号回收
function DeleteSbkTitle()
	local oldWinGuildId = System.getOldSbkGuildId()

	if not oldWinGuildId then
		--print("not exist oldWinGuildId")
		return
	end
	if oldWinGuildId == 0 then
		--print("oldWinGuildId = 0")
		return
	end

	--print("oldWinGuildId ="..oldWinGuildId)

	local pGuild = Guild.getGuild(oldWinGuildId)
	local guildLeaderId = Guild.getGuildLeaderId(oldWinGuildId)
	local onLineGuildPlayers = LuaHelp.getGuildMemberList(pGuild) or {}
	for idx,player in ipairs(onLineGuildPlayers) do
		local actorId = Actor.getActorId(player)
		if actorId == guildLeaderId then
			Actor.setSocialMask(player, smIsSbkCityMaster, false)
			Actor.delTopTitle(player,Title.SbkOwner)
			Actor.delBuffById(player, GuildSiegeConfig.dragonRoleBuffId)
		else
			--Actor.delTopTitle(player,Title.SbkMember)
			local vocation = Actor.getIntProperty(player, PROP_ACTOR_VOCATION)
			for idx = 1, #GuildSiegeConfig.normalRoleBuffId[vocation] do
				if Actor.hasBuffById(player, GuildSiegeConfig.normalRoleBuffId[vocation][idx]) then
					Actor.delBuffById(player, GuildSiegeConfig.normalRoleBuffId[vocation][idx])
				end
			end
		end
	end
end

--登陆玩家检测沙巴克称号和龙袍
function LoginPlayerSbkTitleChange(sysarg)
	local winGuildId = System.getSbkGuildId()
	if winGuildId and winGuildId ~= 0 and winGuildId == Actor.getGuildId(sysarg) then
		local actorId = Actor.getActorId(sysarg)
		local guildOwnerId = Guild.getSbkCityOwner()
        if guildOwnerId == actorId then
            if not Actor.hasTopTitle(sysarg, Title.SbkOwner) then
                Actor.addTopTitle(sysarg,Title.SbkOwner)
                Actor.setSocialMask(sysarg, smIsSbkCityMaster, true)
                Actor.addBuffById(sysarg, GuildSiegeConfig.dragonRoleBuffId)
            end
        else
            local vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
            for idx = 1, #GuildSiegeConfig.normalRoleBuffId[vocation] do
                if not Actor.hasBuffById(sysarg, GuildSiegeConfig.normalRoleBuffId[vocation][idx]) then
                    Actor.addBuffById(sysarg, GuildSiegeConfig.normalRoleBuffId[vocation][idx])
                end
            end

            if Actor.getSocialMask(sysarg, smIsSbkCityMaster) then
				Actor.setSocialMask(sysarg, smIsSbkCityMaster, false)
			end


			if Actor.hasTopTitle(sysarg, Title.SbkOwner) then
				Actor.delTopTitle(sysarg,Title.SbkOwner)
			end

			if Actor.hasBuffById(sysarg, GuildSiegeConfig.dragonRoleBuffId)then
				Actor.delBuffById(sysarg, GuildSiegeConfig.dragonRoleBuffId)
			end

        end
		

		--[[
		if not Actor.hasTopTitle(sysarg, Title.SbkMember) and guildOwnerId ~= actorId then
			Actor.addTopTitle(sysarg,Title.SbkMember)
		end
		]]
	else
		if Actor.hasTopTitle(sysarg, Title.SbkOwner) then
			Actor.delTopTitle(sysarg,Title.SbkOwner)
		end

		--[[
		if Actor.hasTopTitle(sysarg, Title.SbkMember) then
			Actor.delTopTitle(sysarg,Title.SbkMember)
		end
		]]

		local vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
		for idx = 1, #GuildSiegeConfig.normalRoleBuffId[vocation] do
			if Actor.hasBuffById(sysarg, GuildSiegeConfig.normalRoleBuffId[vocation][idx]) then
				Actor.delBuffById(sysarg, GuildSiegeConfig.normalRoleBuffId[vocation][idx])
			end
		end

		if Actor.hasBuffById(sysarg, GuildSiegeConfig.dragonRoleBuffId) then
			Actor.delBuffById(sysarg, GuildSiegeConfig.dragonRoleBuffId)
		end
			
		if Actor.getSocialMask(sysarg, smIsSbkCityMaster) then
			Actor.setSocialMask(sysarg, smIsSbkCityMaster, false)
		end
	end
end

--胜利行会奖励
function SendSbkWinGuildReward()
	local winGuildId = System.getSbkGuildId()
	if not winGuildId then
		return
	end
	if winGuildId == 0 then
		return
	end

	local pGuild = Guild.getGuild(winGuildId)

	if not pGuild then
		return
	end

	local guildLeaderId = Guild.getSbkCityOwner()
	local rankPtr = Ranking.getRanking(RankList[RANK_SBK_WIN_GUILD_PLAYERS].strName)
	local rankCount = Ranking.getRankItemCount(rankPtr)

	local logId = LogIds.SbkWarWinGuildAwardLogId
	local logStr = Lang.LogTips.SbkWarWinGuildAward
	local title = {}
	local content = {}
	title[1] = Lang.GuildLang.GuildSeige006
	content[1] = Lang.GuildLang.GuildSeige007
	title[2] = Lang.GuildLang.GuildSeige008
	content[2] = Lang.GuildLang.GuildSeige009
	title[3] = Lang.GuildLang.GuildSeige010
	content[3] = Lang.GuildLang.GuildSeige011
	title[4] = Lang.GuildLang.GuildSeige012
	content[4] = Lang.GuildLang.GuildSeige013
	
	if guildLeaderId == 0 then
		return
	end

	--print("SendSbkWinGuildReward winGuildId = "..winGuildId)
	--print("SendSbkWinGuildReward guildLeaderId = "..guildLeaderId)

	--会长奖励
	Awards.GiveToMailById(guildLeaderId, GuildSiegeConfig.winGuildAward[1].awards, title[1], content[1], logId, logStr)

	local awardPlayers = {}
	table.insert(awardPlayers, guildLeaderId)

	rewardTable = {}

	local awardLen = #GuildSiegeConfig.winGuildAward

	local totalNum = 0
	for ii = 1, awardLen do
		if GuildSiegeConfig.winGuildAward[ii].num > 0 then
			for idx = 1,  GuildSiegeConfig.winGuildAward[ii].num do
				rewardTable[idx + totalNum] = ii 
			end
			totalNum = GuildSiegeConfig.winGuildAward[ii].num + totalNum
		end
	end

	local curNum = 1

	for idx = 1, rankCount do
		--print("SendSbkWinGuildReward idx = "..idx)
		local item = Ranking.getItemFromIndex(rankPtr, idx - 1)
		if item then
			local actorId = tonumber(Ranking.getId(item))
			--print("SendSbkWinGuildReward actorId1 = "..actorId)
			if actorId == guildLeaderId then
			else
				curNum = curNum + 1
				local awardIndex = rewardTable[curNum]
				--print("SendSbkWinGuildReward awardIndex1 = "..awardIndex)
				if not awardIndex then
					awardIndex = awardLen
				end
				--print("SendSbkWinGuildReward awardIndex2 = "..awardIndex)
				Awards.GiveToMailById(actorId, GuildSiegeConfig.winGuildAward[awardIndex].awards, title[awardIndex], content[awardIndex], logId, logStr)
			end
		end
	end

	local siegeSceneList = {GuildSiegeConfig.PalaceSceenId, GuildSiegeConfig.FightSceenId}
	for i,v in ipairs(siegeSceneList) do
		local playerList = LuaHelp.getSceneActorListById(v) or {}
		for i2,v2 in ipairs(playerList) do
			local actorId = Actor.getActorId(v2)
			local item = Ranking.getItemPtrFromId(rankPtr, actorId)
			--print("SendSbkWinGuildReward playerGuildId = "..Actor.getGuildId(v2))
			if winGuildId == Actor.getGuildId(v2) and guildLeaderId ~= actorId and not item then
				--print("SendSbkWinGuildReward actorId2 = "..actorId)
				Awards.GiveToMailById(actorId, GuildSiegeConfig.winGuildAward[awardLen].awards, title[awardLen], content[awardLen], logId, logStr)
			end
		end
	end

end

--积分最高行会奖励
function SendSbkScoreGuildReward(maxScoreGuildId)

	if not maxScoreGuildId then
		--print("not maxScoreGuildId")
		return
	end

	if maxScoreGuildId == 0 then
		--print("maxScoreGuildId = 0")
		return
	end

	--print("SendSbkScoreGuildReward maxScoreGuildId = "..maxScoreGuildId)

	local pGuild = Guild.getGuild(maxScoreGuildId)

	if not pGuild then
		--print("SendSbkScoreGuildReward not guild ")
		return
	end

	local guildLeaderId = Guild.getGuildLeaderId(maxScoreGuildId)

	if guildLeaderId == 0 then
		--print("SendSbkScoreGuildReward guildLeaderId = 0")
		return
	end

	local rankPtr = Ranking.getRanking(RankList[RANK_SBK_MAXSCORE_PLAYERS].strName)
	local rankCount = Ranking.getRankItemCount(rankPtr)
	--print("SendSbkScoreGuildReward rankCount = "..rankCount)


	local logId = LogIds.SbkWarScoreMaxAwardLogId
	local logStr = Lang.LogTips.SbkWarScoreMaxAward
	local title = {}
	local content = {}
	title[1] = Lang.GuildLang.GuildSeige014
	content[1] = Lang.GuildLang.GuildSeige015
	title[2] = Lang.GuildLang.GuildSeige016
	content[2] = Lang.GuildLang.GuildSeige017
	title[3] = Lang.GuildLang.GuildSeige018
	content[3] = Lang.GuildLang.GuildSeige019
	title[4] = Lang.GuildLang.GuildSeige020
	content[4] = Lang.GuildLang.GuildSeige021

	--print("SendSbkScoreGuildReward maxScoreGuildId = "..maxScoreGuildId)
	--print("SendSbkScoreGuildReward guildLeaderId = "..guildLeaderId)

	--会长奖励
	Awards.GiveToMailById(guildLeaderId, GuildSiegeConfig.winGuildScoreAward[1].awards, title[1], content[1], logId, logStr)

	local awardPlayers = {}
	table.insert(awardPlayers, guildLeaderId)

	rewardTable = {}

	local awardLen = #GuildSiegeConfig.winGuildScoreAward

	local totalNum = 0
	for ii = 1, awardLen do
		if GuildSiegeConfig.winGuildScoreAward[ii].num > 0 then
			for idx = 1,  GuildSiegeConfig.winGuildScoreAward[ii].num do
				rewardTable[idx + totalNum] = ii 
			end
			totalNum = GuildSiegeConfig.winGuildScoreAward[ii].num + totalNum
		end
	end

	local curNum = 1
	
	for idx = 1, rankCount do
		--print("SendSbkScoreGuildReward idx = "..idx)
		local item = Ranking.getItemFromIndex(rankPtr, idx - 1)
		if item then
			local actorId = tonumber(Ranking.getId(item))
			--print("SendSbkScoreGuildReward actorId1 = "..actorId)
			if actorId == guildLeaderId then
			else
				curNum = curNum + 1
				local awardIndex = rewardTable[curNum]
				--print("SendSbkScoreGuildReward awardIndex1 = "..awardIndex)
				if not awardIndex then
					awardIndex = awardLen
				end
				--print("SendSbkScoreGuildReward awardIndex2 = "..awardIndex)
				Awards.GiveToMailById(actorId, GuildSiegeConfig.winGuildScoreAward[awardIndex].awards, title[awardIndex], content[awardIndex], logId, logStr)
			end
		end
	end

	local siegeSceneList = {GuildSiegeConfig.PalaceSceenId, GuildSiegeConfig.FightSceenId}
	for i,v in ipairs(siegeSceneList) do
		local playerList = LuaHelp.getSceneActorListById(v) or {}
		for i2,v2 in ipairs(playerList) do
			local actorId = Actor.getActorId(v2)
			local item = Ranking.getItemPtrFromId(rankPtr, actorId)
			--print("SendSbkScoreGuildReward playerGuildId = "..Actor.getGuildId(v2))
			if maxScoreGuildId == Actor.getGuildId(v2) and guildLeaderId ~= actorId and not item then
				--print("SendSbkScoreGuildReward actorId2 = "..actorId)
				Awards.GiveToMailById(actorId, GuildSiegeConfig.winGuildScoreAward[awardLen].awards, title[awardLen], content[awardLen], logId, logStr)
			end
		end
	end
	
end 

--把玩家从皇宫里面踢出来
function KickAllPlayerInPalace()
	local playerList = LuaHelp.getSceneActorListById(GuildSiegeConfig.FightSceenId) or {}
	for k , v in ipairs(playerList) do
		Actor.enterScene( v, unpack(GuildSiegeConfig.exitPos))
	end

	OnInitSbkState()
end

--设置皇宫入口不可见
function OnInitSbkState()
	SetPalaceTeleportVisible(false)
	--SbkGuildTaxHandle()
	InitNpcStatueName()
end

--初始化城主雕像名字
function InitNpcStatueName()
	local pNpc = Fuben.getNpcPtrById(GuildSiegeConfig.StatusSceenId,74)
	if pNpc then
		local winGuildId = System.getSbkGuildId()
		if winGuildId and winGuildId ~= 0 then
			local leader = Guild.getGuildLeaderId( winGuildId )
			if leader then
				local actorName = System.getSbkPostionName(stRealMaster, 0)
				Actor.changeShowName(pNpc,10, actorName)
				local actorSex = Guild.getGuildSbkLeaderSex()
				Actor.changeEntityModel(pNpc,10, GuildSiegeConfig.CityOwnerStatusModel[actorSex+1])
				return
			end
		end	
		Actor.changeShowName(pNpc,10, Lang.EntityName.n00074)
		Actor.changeEntityModel(pNpc,10, GuildSiegeConfig.CityOwnerStatusModel[1])
	end
end

function OnGuildSbkChangeMember(sysarg, opType)
	if opType == 1 then
		local vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
		for idx = 1, #GuildSiegeConfig.normalRoleBuffId[vocation] do
			if not Actor.hasBuffById(sysarg, GuildSiegeConfig.normalRoleBuffId[vocation][idx]) then
				Actor.addBuffById(sysarg, GuildSiegeConfig.normalRoleBuffId[vocation][idx])
			end
		end
	elseif opType == 0 then
		local vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
		for idx = 1, #GuildSiegeConfig.normalRoleBuffId[vocation] do
			if Actor.hasBuffById(sysarg, GuildSiegeConfig.normalRoleBuffId[vocation][idx]) then
				Actor.delBuffById(sysarg, GuildSiegeConfig.normalRoleBuffId[vocation][idx])
			end
		end
	end
end

--城主变化
function OnGuildSbkChangeLeader(oldSbkOwnerId, newSbkOwnerId)
	local oldOwner = Actor.getActorById(oldSbkOwnerId)
	local newOwner = Actor.getActorById(newSbkOwnerId)

	if newOwner then
		if not Actor.hasTopTitle(newOwner, Title.SbkOwner) then
			Actor.addTopTitle(newOwner,Title.SbkOwner)
		end
		
		local vocation = Actor.getIntProperty(newOwner, PROP_ACTOR_VOCATION)
		for idx = 1, #GuildSiegeConfig.normalRoleBuffId[vocation] do
			if Actor.hasBuffById(newOwner, GuildSiegeConfig.normalRoleBuffId[vocation][idx]) then
				Actor.delBuffById(newOwner, GuildSiegeConfig.normalRoleBuffId[vocation][idx])
			end
		end

		if not Actor.hasBuffById(newOwner, GuildSiegeConfig.dragonRoleBuffId) then
			Actor.addBuffById(newOwner, GuildSiegeConfig.dragonRoleBuffId)
		end
	end

	if oldOwner then
		if Actor.hasTopTitle(oldOwner, Title.SbkOwner) then
			Actor.delTopTitle(oldOwner,Title.SbkOwner)
		end

		local vocation = Actor.getIntProperty(oldOwner, PROP_ACTOR_VOCATION)
		for idx = 1, #GuildSiegeConfig.normalRoleBuffId[vocation] do
			if not Actor.hasBuffById(oldOwner, GuildSiegeConfig.normalRoleBuffId[vocation][idx]) then
				Actor.addBuffById(oldOwner, GuildSiegeConfig.normalRoleBuffId[vocation][idx])
			end
		end

		if Actor.hasBuffById(oldOwner, GuildSiegeConfig.dragonRoleBuffId) then
			Actor.delBuffById(oldOwner, GuildSiegeConfig.dragonRoleBuffId)
		end
	end
end

--删除旧行会的名字
function OnOldSbkGuildResetName()
	local oldGuildId = System.getOldSbkGuildId()

	local winGuildId = System.getSbkGuildId()
	if not oldGuildId then
		return
	end
	if oldGuildId == 0 then
		return
	end

	if winGuildId == oldGuildId then
		return
	end

	local pGuild = Guild.getGuild(oldGuildId)

	if not pGuild then
		return
	end

	local onLineGuildPlayers = LuaHelp.getGuildMemberList(pGuild) or {}
	for idx,player in ipairs(onLineGuildPlayers) do
		Actor.ResetShowName(player)
	end
end


--保存排行榜数据
function SaveGuildRank()
	local rankPtr = Ranking.getRanking(RankList[RANK_SBK_GUILD_LIST].strName)
	local rankCount = Ranking.getRankItemCount(rankPtr)
	local Id = rankCount + 1
	local time = System.getCurrMiniTime()


	local oldGuildId = System.getOldSbkGuildId()
	local winGuildId = System.getSbkGuildId()
	local guildName = Guild.getGuildName(winGuildId)
	if not guildName then
		guildName = Guild.getGuildName(oldGuildId)
	end
	if not guildName then
		guildName = ""
	end
	gRankMgr_SetRank(Id, RANK_SBK_GUILD_LIST, time,  guildName)

	local data = gRankMgr_GetValueByIndx(0, RANK_SBK_GUILD_LIST, 1)
	local myData = BaseFuc_unserialize(data)

	if not myData then
		myData = {}
	end

	local sdvar = System.getDyanmicVar()

	local sbkPosition = LuaHelp.getSbkPositionId()
	myData.sbkPosition = {}
	for idx = 1, #sbkPosition do
		myData.sbkPosition[idx] = System.getValueByPtr(sbkPosition[idx])
	end

	myData.oldGuildId = oldGuildId
	myData.winGuildId = winGuildId
	myData.sbkCheckWinGuild = sdvar.sbkCheckWinGuild
	myData.sbkWarStartTime = sdvar.sbkWarStartTime
	myData.sbkStatusLive = sdvar.sbkStatusLive
	myData.time = time
	myData.guildSbkTempOccupyGuildId = sdvar.guildSbkTempOccupyGuildIds

	myData.sbkGuildMaxScoreGuildId = sdvar.sbkGuildMaxScoreGuildId
	myData.sbkOldGuildMaxScoreGuildId = sdvar.sbkOldGuildMaxScoreGuildId

	local newData = BaseFuc_serialize(myData)
	gRankMgr_SetRankEx(Id, RANK_SBK_GUILD_LIST, 1, newData, guildName)

end

--更改排行榜数据
function changeSaveGuildRank()
	local rankPtr = Ranking.getRanking(RankList[RANK_SBK_GUILD_LIST].strName)
	local rankCount = Ranking.getRankItemCount(rankPtr)

	local time = System.getCurrMiniTime()
	local data = gRankMgr_GetValueByIndx(0, RANK_SBK_GUILD_LIST, 1)
	local myData = BaseFuc_unserialize(data)

	if not myData then
		myData = {}
	end

	local Id = rankCount

	if myData and myData.time and not System.isSameDay(time, myData.time) then
		SaveGuildRank()
		data = gRankMgr_GetValueByIndx(0, RANK_SBK_GUILD_LIST, 1)
		myData = BaseFuc_unserialize(data)
		Id = rankCount + 1
	elseif Id == 0 then
		Id = 1
	end

	local sbkPosition = LuaHelp.getSbkPositionId()
	myData.sbkPosition = {}
	for idx = 1, #sbkPosition do
		table.insert(myData.sbkPosition ,System.getValueByPtr(sbkPosition[idx]))
	end

	local oldGuildId = System.getOldSbkGuildId()
	local winGuildId = System.getSbkGuildId()

	local guildName = Guild.getGuildName(winGuildId)
	if not guildName then
		guildName = Guild.getGuildName(oldGuildId)
	end
	if not guildName then
		guildName = ""
	end

	local sdvar = System.getDyanmicVar()
	myData.oldGuildId = oldGuildId
	myData.winGuildId = winGuildId
	myData.sbkCheckWinGuild = sdvar.sbkCheckWinGuild
	myData.sbkWarStartTime = sdvar.sbkWarStartTime
	myData.sbkStatusLive = sdvar.sbkStatusLive
	myData.time = time
	myData.guildSbkTempOccupyGuildId = sdvar.guildSbkTempOccupyGuildId

	myData.sbkGuildMaxScoreGuildId = sdvar.sbkGuildMaxScoreGuildId
	myData.sbkOldGuildMaxScoreGuildId = sdvar.sbkOldGuildMaxScoreGuildId

	local newData = BaseFuc_serialize(myData)
	gRankMgr_SetRankEx(Id, RANK_SBK_GUILD_LIST, 1, newData, guildName)
end

--攻城战重启处理
function onLoadSbkGuild()
	local time = System.getCurrMiniTime()
	local SbkSignUpTime = GuildConfig.SbkSignUpTime
	local rankPtr = Ranking.getRanking(RankList[RANK_SBK_GUILD_LIST].strName)
	if not rankPtr then
		loadSbkGuildNoDataHandler()
		return
	end
	local rankCount = Ranking.getRankItemCount(rankPtr)
	local myData
	if rankCount > 0 then
		local data = gRankMgr_GetValueByIndx(0, RANK_SBK_GUILD_LIST, 1)
		myData = BaseFuc_unserialize(data)

		local sdvar = System.getDyanmicVar()
		--不到18点或者不在攻城期间
		if not CheckSbkGuildWarTime() or System.getToday() + 18*3600 > time then
			System.setSbkGuildId(myData.winGuildId or 0)
			System.setSbkOldGuildId(myData.oldGuildId or 0)

			local nDays = System.getDaysSinceOpenServer()
			if nDays <= SbkSignUpTime.openDay then
				System.setSbkSignState(0)
			else
				System.setSbkSignState(1)
			end
			
			if SbkSignUpTime.combineDay >= 0 then
				nDays = System.getDaysSinceCombineServer()
				if nDays > 0 then -- 合过服了
					if nDays <= SbkSignUpTime.combineDay then
						System.setSbkSignState(0)
					else
						System.setSbkSignState(1)
					end
				end		
			end

			System.endSbkGuildWar()

			sdvar.setSbkPositionList = 1

			sdvar.sbkGuildMaxScoreGuildId = myData.sbkGuildMaxScoreGuildId

			--[[
			if myData.sbkPosition and type(myData.sbkPosition) == 'table' then
				for idx = 1, #myData.sbkPosition do
					Guild.setSbkGuildPosition(myData.sbkPosition[idx] or 0, idx + 1)
				end
			end
			]]

		--不到20点
		elseif CheckSbkGuildWarTime() and System.getToday() + 20*3600 > time then
			if myData and myData.time and not System.isSameDay(time, myData.time) then
				System.setSbkGuildId(myData.winGuildId or 0)
				sdvar.sbkGuildMaxScoreGuildId = myData.sbkGuildMaxScoreGuildId
				System.stopSbkGuildWarSign()	
				Guild.clearSbkGuildPosition()
				InitNpcStatueName()

				--排行榜数据清理	
				gRankMgr_Clear(RANK_SBK_SCORE)
				gRankMgr_Clear(RANK_SBK_GUILD_SCORE)
				gRankMgr_Clear(RANK_SBK_WIN_GUILD_PLAYERS)
				gRankMgr_Clear(RANK_SBK_MAXSCORE_PLAYERS)

				SaveGuildRank()
				gRankMgr_Save(RANK_SBK_GUILD_LIST)
			else
				Guild.clearSbkGuildPosition()
				System.setSbkOldGuildId(myData.oldGuildId or 0)
				sdvar.sbkOldGuildMaxScoreGuildId = myData.sbkOldGuildMaxScoreGuildId
			end
		--不到20点10分
		elseif CheckSbkGuildWarTime() and System.getToday() + 20*3600 + 10*60 > time then
			if myData and myData.time and not System.isSameDay(time, myData.time) then
				System.setSbkGuildId(myData.winGuildId or 0)
				sdvar.sbkGuildMaxScoreGuildId = myData.sbkGuildMaxScoreGuildId
				System.stopSbkGuildWarSign()	
				Guild.clearSbkGuildPosition()
				InitNpcStatueName()

				--排行榜数据清理	
				gRankMgr_Clear(RANK_SBK_SCORE)
				gRankMgr_Clear(RANK_SBK_GUILD_SCORE)
				gRankMgr_Clear(RANK_SBK_WIN_GUILD_PLAYERS)
				gRankMgr_Clear(RANK_SBK_MAXSCORE_PLAYERS)
				SaveGuildRank()

				sdvar.sbkWarStartTime = System.getToday() + 20*3600
				sdvar.sbkStatusLive = nil
				sdvar.sbkCheckWinGuild = nil


				System.startSbkGuildWar()

				Actor.unregScriptCallback(System.getGlobalNpc(), "OnGetSbkExpInTheMap")
				Actor.regScriptTimer(System.getGlobalNpc(), 0, GuildSiegeConfig.LoopTime, GuildSiegeConfig.LoopTime, 1, "OnGetSbkExpInTheMap") 	

				CreateSbkStatus()

				changeSaveGuildRank()

				gRankMgr_Save(RANK_SBK_GUILD_LIST)
			else
				System.setSbkOldGuildId(myData.oldGuildId or 0)
				sdvar.sbkOldGuildMaxScoreGuildId = myData.sbkOldGuildMaxScoreGuildId
				sdvar.sbkWarStartTime = System.getToday() + 20*3600
				sdvar.sbkStatusLive = myData.sbkStatusLive
				sdvar.sbkCheckWinGuild = myData.sbkCheckWinGuild

				System.startSbkGuildWar()

				Actor.unregScriptCallback(System.getGlobalNpc(), "OnGetSbkExpInTheMap")
				Actor.regScriptTimer(System.getGlobalNpc(), 0, GuildSiegeConfig.LoopTime, GuildSiegeConfig.LoopTime, 1, "OnGetSbkExpInTheMap") 	
				if sdvar.sbkStatusLive and sdvar.sbkStatusLive > 0 then
					CreateSbkStatus()
				end

				changeSaveGuildRank()
				gRankMgr_Save(RANK_SBK_GUILD_LIST)
			end
			--不到21点
		elseif CheckSbkGuildWarTime() and System.getToday() + 21*3600 > time then
			if myData and myData.time and not System.isSameDay(time, myData.time) then
				System.setSbkGuildId(myData.winGuildId or 0)
				sdvar.sbkGuildMaxScoreGuildId = myData.sbkGuildMaxScoreGuildId
				System.stopSbkGuildWarSign()	
				Guild.clearSbkGuildPosition()
				InitNpcStatueName()

				--排行榜数据清理	
				gRankMgr_Clear(RANK_SBK_SCORE)
				gRankMgr_Clear(RANK_SBK_GUILD_SCORE)
				gRankMgr_Clear(RANK_SBK_WIN_GUILD_PLAYERS)
				gRankMgr_Clear(RANK_SBK_MAXSCORE_PLAYERS)
				SaveGuildRank()

				sdvar.sbkWarStartTime = System.getToday() + 20*3600
				sdvar.sbkStatusLive = 1
				sdvar.sbkCheckWinGuild = 1


				System.startSbkGuildWar()

				Actor.unregScriptCallback(System.getGlobalNpc(), "OnGetSbkExpInTheMap")
				Actor.regScriptTimer(System.getGlobalNpc(), 0, GuildSiegeConfig.LoopTime, GuildSiegeConfig.LoopTime, 1, "OnGetSbkExpInTheMap") 	

				CreateSbkStatus()

				changeSaveGuildRank()
				gRankMgr_Save(RANK_SBK_GUILD_LIST)

			else
				System.setSbkOldGuildId(myData.oldGuildId or 0)
				sdvar.sbkOldGuildMaxScoreGuildId = myData.sbkOldGuildMaxScoreGuildId
				sdvar.sbkWarStartTime = System.getToday() + 20*3600
				sdvar.sbkStatusLive = myData.sbkStatusLive
				sdvar.sbkCheckWinGuild = 1
				sdvar.guildSbkTempOccupyGuildId = myData.guildSbkTempOccupyGuildId or System.getOldSbkGuildId()
				if sdvar.guildSbkTempOccupyGuildId and sdvar.guildSbkTempOccupyGuildId == 0 then
					sdvar.guildSbkTempOccupyGuildId = System.getOldSbkGuildId()
				end
					
				System.startSbkGuildWar()

				Actor.unregScriptCallback(System.getGlobalNpc(), "OnGetSbkExpInTheMap")
				Actor.regScriptTimer(System.getGlobalNpc(), 0, GuildSiegeConfig.LoopTime, GuildSiegeConfig.LoopTime, 1, "OnGetSbkExpInTheMap") 	

				if sdvar.sbkStatusLive and sdvar.sbkStatusLive > 0 then
					CreateSbkStatus()
				end

				changeSaveGuildRank()
				gRankMgr_Save(RANK_SBK_GUILD_LIST)
			end
			--21点之后的处理
		elseif CheckSbkGuildWarTime() and System.getToday() + 21*3600 <= time then
			--local dvar = System.getDyanmicVar()
			--dvar.guildSeigeTaxCanGet = 1
			if myData and myData.time and not System.isSameDay(time, myData.time) then
				System.setSbkGuildId(myData.winGuildId or 0)
				System.setSbkOldGuildId(myData.oldGuildId or 0)

				sdvar.sbkGuildMaxScoreGuildId = myData.sbkGuildMaxScoreGuildId

				System.setSbkSignState(1)

				sdvar.setSbkPositionList = 1

				--[[
				if myData.sbkPosition and type(myData.sbkPosition) == 'table' then
					for idx = 1, #myData.sbkPosition do
						Guild.setSbkGuildPosition(myData.sbkPosition[idx] or 0, idx + 1)
					end
				end
				]]
			else
				if myData.winGuildId and myData.winGuildId > 0 then
					System.setSbkGuildId(myData.winGuildId or 0)
					System.setSbkOldGuildId(myData.oldGuildId or 0)

					sdvar.sbkGuildMaxScoreGuildId = myData.sbkGuildMaxScoreGuildId

					System.setSbkSignState(1)

					sdvar.setSbkPositionList = 1
					--[[
					if myData.sbkPosition and type(myData.sbkPosition) == 'table' then
						for idx = 1, #myData.sbkPosition do
							Guild.setSbkGuildPosition(myData.sbkPosition[idx] or 0, idx + 1)
						end
					end
					]]
				elseif myData.oldGuildId and myData.oldGuildId > 0 then
					System.setSbkGuildId(myData.oldGuildId)
					sdvar.sbkGuildMaxScoreGuildId = myData.sbkOldGuildMaxScoreGuildId
					sdvar.sbkRestartNeedSendCityPosition = 1

					InitNpcStatueName()

					System.setSbkSignState(1)
				end
			end
		end
	else
		loadSbkGuildNoDataHandler()
		return
	end
end

--没数据处理
function loadSbkGuildNoDataHandler()
	local SbkSignUpTime = GuildConfig.SbkSignUpTime
	local sdvar = System.getDyanmicVar()
	local time = System.getCurrMiniTime()
	if not CheckSbkGuildWarTime() or System.getToday() + 18*3600 > time then
		local nDays = System.getDaysSinceOpenServer()
		if nDays <= SbkSignUpTime.openDay then
			System.setSbkSignState(0)
		else
			System.setSbkSignState(1)
		end
		
		if SbkSignUpTime.combineDay >= 0 then
			nDays = System.getDaysSinceCombineServer()
			if nDays > 0 then -- 合过服了
				if nDays <= SbkSignUpTime.combineDay then
					System.setSbkSignState(0)
				else
					System.setSbkSignState(1)
				end
			end		
		end
	elseif CheckSbkGuildWarTime() and System.getToday() + 20*3600 > time then
		System.stopSbkGuildWarSign()	

		--排行榜数据清理	
		gRankMgr_Clear(RANK_SBK_SCORE)
		gRankMgr_Clear(RANK_SBK_GUILD_SCORE)
		gRankMgr_Clear(RANK_SBK_WIN_GUILD_PLAYERS)
		gRankMgr_Clear(RANK_SBK_MAXSCORE_PLAYERS)
		SaveGuildRank()
		gRankMgr_Save(RANK_SBK_GUILD_LIST)
	elseif CheckSbkGuildWarTime() and System.getToday() + 20*3600 + 10*60 > time then
		sdvar.sbkWarStartTime = System.getToday() + 20*3600
		sdvar.sbkStatusLive = nil
		sdvar.sbkCheckWinGuild = nil

		System.startSbkGuildWar()

		Actor.unregScriptCallback(System.getGlobalNpc(), "OnGetSbkExpInTheMap")
		Actor.regScriptTimer(System.getGlobalNpc(), 0, GuildSiegeConfig.LoopTime, GuildSiegeConfig.LoopTime, 1, "OnGetSbkExpInTheMap") 	

		CreateSbkStatus()

		changeSaveGuildRank()
		gRankMgr_Save(RANK_SBK_GUILD_LIST)
	elseif CheckSbkGuildWarTime() and System.getToday() + 21*3600 > time then
		sdvar.sbkWarStartTime = System.getToday() + 20*3600
		sdvar.sbkStatusLive = nil
		sdvar.sbkCheckWinGuild = 1

		System.startSbkGuildWar()

		Actor.unregScriptCallback(System.getGlobalNpc(), "OnGetSbkExpInTheMap")
		Actor.regScriptTimer(System.getGlobalNpc(), 0, GuildSiegeConfig.LoopTime, GuildSiegeConfig.LoopTime, 1, "OnGetSbkExpInTheMap") 	

		CreateSbkStatus()

		changeSaveGuildRank()
		gRankMgr_Save(RANK_SBK_GUILD_LIST)
	elseif CheckSbkGuildWarTime() and System.getToday() + 21*3600 <= time then
		System.setSbkSignState(1)
	end
end

--攻城战结束后没经过结算点重启，将原来的占有方的副城主和将军等还给他们
function RestartSendCityPosition()
	InitNpcStatueName()
	local sdvar = System.getDyanmicVar()
	if sdvar.sbkRestartNeedSendCityPosition and sdvar.sbkRestartNeedSendCityPosition == 1 then
		sdvar.sbkRestartNeedSendCityPosition = nil
		SendSbkCityPosition()
		changeSaveGuildRank()
		gRankMgr_Save(RANK_SBK_GUILD_LIST)
	elseif sdvar.setSbkPositionList and sdvar.setSbkPositionList == 1 then
		sdvar.setSbkPositionList = nil

		local data = gRankMgr_GetValueByIndx(0, RANK_SBK_GUILD_LIST, 1)
		myData = BaseFuc_unserialize(data)

		if myData.sbkPosition and type(myData.sbkPosition) == 'table' then
			for idx = 1, #myData.sbkPosition do
				Guild.setSbkGuildPosition(myData.sbkPosition[idx] or 0, idx + 1)
			end
		end
	end
end


--Gm去掉占领方的外观
function GmSbkBackAppear()
	Guild.clearSbkGuildPosition()

	DeleteSbkTitle()

	InitNpcStatueName()

	--排行榜数据清理	
	gRankMgr_Clear(RANK_SBK_SCORE)
	gRankMgr_Clear(RANK_SBK_GUILD_SCORE)
	gRankMgr_Clear(RANK_SBK_WIN_GUILD_PLAYERS)
	gRankMgr_Clear(RANK_SBK_MAXSCORE_PLAYERS)


	SaveGuildRank()
	gRankMgr_Save(RANK_SBK_GUILD_LIST)
end
--[[
function SbkGuildTaxHandle()
	if not CheckSbkGuildWarTime() then
		local dvar = System.getDyanmicVar()
		dvar.guildSeigeTaxCanGet = 1
		return
	end
	local var = System.getStaticVar()
	local time = System.getCurrMiniTime()
	local compTime = var.guildSeigeTaxRefreshTime or 0
	if System.isSameDay(compTime, time) then
		return 
	end
	var.szGuildSeigeTaxCanGet = var.szGuildSeigeTaxValue or 0
	var.szGuildSeigeTaxValue = 0
	var.guildSeigeTaxRefreshTime = time
	var.guildSeigeTaxGetState = 0

	local dvar = System.getDyanmicVar()
	dvar.guildSeigeTaxCanGet = 0
end

function GetSbkGuildTax(sysarg)
	local var = System.getStaticVar()
	if var.guildSeigeTaxGetState == 1 then
		return false
	end
	if Guild.getSbkCityOwner() ~= Actor.getActorId(sysarg) then
		return false
	end

	var.guildSeigeTaxGetState = 1
	Actor.addMoney( sysarg, mtBindCoin, var.szGuildSeigeTaxCanGet, LogIds.GuildSbkTaxLogId, Lang.LogTips.GuildSbkTax)
	return true
end
]]

function resetGuildSbkPosition()
	local winGuildId = System.getSbkGuildId()
	if not winGuildId or winGuildId == 0 then
		return
	end

	SendSbkCityPosition()

	local rankPtr = Ranking.getRanking(RankList[RANK_SBK_GUILD_LIST].strName)
	local rankCount = Ranking.getRankItemCount(rankPtr)

	local data = gRankMgr_GetValueByIndx(0, RANK_SBK_GUILD_LIST, 1)
	local myData = BaseFuc_unserialize(data)

	if not myData then
		myData = {}
	end

	local Id = rankCount

	if myData.winGuildId and winGuildId == myData.winGuildId then
		local sbkPosition = LuaHelp.getSbkPositionId()
		myData.sbkPosition = {}
		for idx = 1, #sbkPosition do
			table.insert(myData.sbkPosition ,System.getValueByPtr(sbkPosition[idx]))
		end

		local guildName = Guild.getGuildName(winGuildId)
		if not guildName then
			guildName = ""
		end

		local newData = BaseFuc_serialize(myData)
		gRankMgr_SetRankEx(Id, RANK_SBK_GUILD_LIST, 1, newData, guildName)

		gRankMgr_Save(RANK_SBK_GUILD_LIST)
	end

end
